<template>
    <div class="container">
        <el-row type="flex" justify="space-between">
            <div class="main">
                <h2>发表新攻略</h2>
                <p class="create-desc">
                    分享你的个人游记，让更多人看到哦！
                </p>
                <el-form>
                    <el-form-item>
                        <el-input placeholder="请输入标题" v-model="form.title"/>
                    </el-form-item>

                    <el-form-item>
                        <VueEditor :config="config" ref="vueEditor"/>
                    </el-form-item>

                    <el-form-item>
                        <el-form-item label="选择城市">
                            <el-autocomplete
                                :fetch-suggestions="querySearchAsync"
                                placeholder="请搜索游玩城市"
                                class="el-autocomplete"
                                @select="handleCitySelect"
                                @focus="handleCityFocus"
                                v-model="cityName"
                            ></el-autocomplete>
                        </el-form-item>
                    </el-form-item>
                </el-form>
                <div class="create-button">
                    <el-button type="primary" size="small" @click="handlePublish">发布</el-button> 
                    <span class="submit-side"> 
                        或者 <a href="javascript:;" @click="handleSaveDraft">保存到草稿</a>
                    </span>
                </div>
            </div>
            <div class="aside">
                <div class="draft-box">
                    <h4 class="draft-title">草稿箱（{{$store.state.post.posts.length}}）</h4>
                    <div class="draft-list">
                        <div class="draft-item" v-for="(item, index) in $store.state.post.posts" :key="index">
                            <div class="draft-post-title" @click="handleReEdit(item)">
                                {{item.title}} 
                            </div>
                            <el-row type="flex" justify="space-between">
                                <p>{{item.time}}</p>
                                <div>
                                    <span class="iconfont el-icon-edit" @click="handleReEdit(item)"></span>
                                    <span class="iconfont el-icon-delete" @click="handleDelete(item)"></span>
                                </div>
                                
                            </el-row>
                            
                        </div>
                    </div>
                </div>
            </div>
        </el-row>
    </div>
</template>

<script>
import moment from "moment";
import "quill/dist/quill.snow.css"
import {mapState} from "vuex";
let VueEditor;

// https://zh.nuxtjs.org/guide/async-data#%E4%B8%8A%E4%B8%8B%E6%96%87%E5%AF%B9%E8%B1%A1
if (process.browser) {
    //只在浏览器端才渲染就不会报错了
    VueEditor = require('vue-word-editor').default
}

export default {
    data(){
        return {
            form: {
                title: "",
                content: "",
                city: ""    // 用于保存选中时的city id
            },
            cityName: "", // 用于显示，最后提交把值赋给form.city,
            config: {
                modules: { 
                    // 工具栏
                    toolbar: [
                        ['bold', 'italic', 'underline', 'strike'],        // toggled buttons
                        [{ 'header': 1 }, { 'header': 2 }],               // custom button values
                        ['image'],
                    ]
                },
                // 主题
                theme: 'snow',
                uploadImage: {
                    url: `${this.$axios.defaults.baseURL}/upload`,
                    name: "files",
                    uploadSuccess: (res, insert) => {
                        const file = res.data[0];
                        insert(this.$axios.defaults.baseURL + file.url);
                    },
                },

                uploadVideo: {
                    url: `${this.$axios.defaults.baseURL}/upload`,
                    name: "files",
                    uploadSuccess(res, insert){
                        const file = res.data[0];
                        insert(this.$axios.defaults.baseURL + file.url);
                    },
                }
            },
            isLoading: false,
        }
    },

    // mapState with computed

    components: {
        VueEditor
    },

    methods: {
        querySearchAsync(queryString, cb) {
            if(!queryString){
                return cb([]);
            }
            if(this.isLoading) return;
            
            const {api} = this.$store.state;

            this.$axios({
                url: api.AIRS_CITY,
                params: {
                    name: queryString
                }
            }).then(res => {
                this.isLoading = false;
                
                const {data} = res.data;
                
                const arr = data.map(v => {
                    return {
                        ...v,
                        value: v.name
                    }
                })

                cb(arr);
            })
        },

        handleCitySelect(item){
            this.form.city = item.id;
            this.cityName = item.name
        },

        handleCityFocus(){
            this.form.city = "";
            this.cityName = "";
        },

        // 保存到草稿
        handleSaveDraft(){
            const {commit} = this.$store;

            if(this.form.title.trim() === ""){
                this.$message.warning("标题不能为空");
                return;
            }

            commit("post/addPost", {
                title: this.form.title,
                content:  this.$refs.vueEditor.editor.root.innerHTML,
                cityName: this.cityName,
                time: moment().format(`YYYY-MM-DD`)
            });
        },

        // 从草稿箱编辑
        handleReEdit(item){
            this.form.title = item.title;
            this.$refs.vueEditor.editor.root.innerHTML = item.content;
            this.cityName = item.cityName
        },

        handleDelete(item){
            const {commit} = this.$store;

            this.$confirm('确定删除吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                commit("post/deletePost", {
                    title: item.title
                });
                this.$message({
                    type: 'success',
                    message: '删除成功!'
                });
            })
        },

        handlePublish(){

            // 获取富文本编辑器的内容
            //console.log(this.$refs.vueEditor.editor.getContents())
            this.form.content = this.$refs.vueEditor.editor.root.innerHTML;
            this.form.city = this.form.city || this.cityName;

            const rules = {
                title: {require: true, defaults: this.form.title, message: "请填写标题"},
                content: {require: true, validator: () => {
                    console.log(this.form.content == `<p><br></p>`)
                    return this.form.content == `<p><br></p>`
                }, message: "请填写内容"},
                city: {require: true, defaults: this.form.city, message: "请选择城市" },
            }

            // valid
            let valid = true;
            Object.keys(rules).forEach(v => {
                if(!valid) return;
                const item = rules[v];

                if(item.require){
                    if(!item.defaults && !item.validator){
                        valid = false;
                        
                    }

                    if(item.validator){
                        valid = !item.validator();
                    }
                    
                    if(valid == false){
                        this.$confirm(item.message, '提示', {
                            confirmButtonText: '确定',
                            showCancelButton: false,
                            type: 'warning'
                        })
                    }
                }
            });

            if(!valid) return;

            const {api, user: {userInfo}} = this.$store.state;
            
            this.$axios({
                url: api.POST_CREATE,
                method: "POST",
                data: this.form,
                headers: {
                    Authorization: `Bearer ${userInfo.token}`
                }
            }).then(res => {
                const {status, message} = res.data;
                if(!status){
                    this.$message({
                        message,
                        type: "success"
                    });
                }

                 // 初始化表单
                this.form = {
                    title: "",
                    content: "",
                    city: ""
                }
                this.$refs.vueEditor.editor.root.innerHTML = "";
                this.cityName = "";
            }).catch(err => {

            })
        }
    }
}
</script>

<style scoped lang="less">
    .container{
        width:1000px;
        margin:0 auto;
        padding:20px 0; 
    }

    .main{
        width:750px;

        h2{
            font-weight: normal;
            font-size:22px;
            margin-bottom:10px;
        }

        .create-desc{
            font-size:12px;
            color:#999;
            margin-bottom:10px;
        }
        
        .submit-side{
            margin-left:10px;
            font-size: 14px;
            a{
                color:orange;
                &:hover{
                    text-decoration: underline;
                }
            }
        }

        /deep/ #editor{
            height:400px;
        }
    }

    .aside{
        width:225px;
        .draft-box{
            border:1px #ddd solid;
            padding:10px;
            .draft-title{
                margin-bottom:10px;
                font-weight: normal;
                color:#666;
            }

            .draft-item{
                margin-bottom:10px;
                font-size: 14px;

                .draft-post-title{
                    word-break: break-all;
                    text-overflow: ellipsis;
                    overflow: hidden;
                    display: -webkit-box;
                    -webkit-line-clamp: 2;
                    -webkit-box-orient: vertical;
                    cursor: pointer;
                    &:hover{
                        color:orange;
                        text-decoration: underline;
                    }  
                }

                .iconfont{
                        cursor: pointer;
                    }

                p{
                    color:#999;
                }
            }
        }
    }
</style>
